<?php


namespace app\api\controller\v1;


use app\controller\Base;

use app\model\Baby;
use app\model\Members;
use app\model\Milk;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Validate;
use think\Request;

class BabyFace extends Base
{
    //添加喂食记录
    public function Save(Request $request){

        //获取表单数据
        $data = $request->param();
        halt($data);

        //验证返回
        try {

        }catch (ValidateException $exception){
            //错误返回
            return $this->create([],$exception->getError(),400);
        }

        //TODO 先查询一下有没有添加宝宝
        //$chkBaby = Baby::where('user_id',$data['user_id'])->find();



        //写入数据并返回bb_ID
        $id = Milk::create($data)->getData('bb_id');

        if (empty($id)){
            return $this->create([],'写入失败',400);
        }else{
            return $this->create($id,'写入成功',200);
        }

    }

    //获取最近一条喂养记录，baby中ischoose=1的记录
    public function read(Request $request){

        $data = $request->param();

        $map = [];
//        $map[] = [
//            ['b.user_id','=',$data['user_id']],
//            ['b.bb_id','=',$data['bb_id']]
//            ];
        $map[] = ['b.user_id','=',$data['user_id']];

        if (isset($data['ischoose'])){
            //当有多个娃当时候，默认要拉取的最新一条记录
            if ($data['ischoose']==1){
                $map[] = ['ischoose','=',1];
            }
        }

        if (isset($data['bb_id'])){
            if($data['bb_id']!=0){
                $map[] = ['b.bb_id','=',$data['bb_id']];
            }
        }

//        $bb_id = Baby::where('user_id',$data['user_id'])
//            ->where('ischoose',1)
//            ->field('id')
//            ->find();
//
//        $res = Milk::where('bb_id',$bb_id)->find();
//
//        return $this->create($bb_id['data'],'ok',200);

        //$gl = $res->milk()->where('bb_id',175)->select();

        //在milk中查找body中指定user_id且ischoose为1的数据

        $result = Db::table('zh_baby')->alias('m')
            ->join('zh_milk b','b.bb_id=m.id')
            //->where('ischoose',1)
//            ->where('b.user_id',$data['user_id'])
//            ->where('b.bb_id',$data['bb_id'])
            ->where($map)
            ->order('b.id','desc')
            ->find();


        //TODO：合并接口，读取最后一条记录并获取当前bb_id下当日记录数 2022-03-29
//        $resultCount = Db::table('zh_baby')->alias('m')
//            ->join('zh_milk b','b.bb_id=m.id')
//            ->where($map)
//            ->where('status',0)->whereDay('create_time')->count('bb_id');

        //return $this->create($result,'ok',200);


//        halt($map);

        //验证输入的参数合法性，参数为整型
//        if (!Validate::isInteger($id)){
//            return $this->create([],'参数不合法',400);
//        }

        //查找指定小孩ID的最近一条记录
        //$data = Milk::where('bb_id',$id)->order('id','desc')->find();
        //$result = Milk::where($map)->order('id','desc')->find();

        if (empty($result)){
            return $this->create($result,'没有数据',204);
        }else{
            return $this->create($result,'请求成功',200);
        }

    }

    //获取指定用户user_id/小孩bb_id的所有记录
    public function ReadUserLog(Request $request){

        $rqdata = $request->param();

        $map = [];
        $map[] = ['user_id','=',$rqdata['user_id']];

        if (!empty($rqdata['bb_id'])){
            $map[] = ['bb_id','=',$rqdata['bb_id']];
        }

        $data = Milk::Where($map)->limit(5)->order('id','desc')->select();

        if($data->isEmpty()){
            return $this->create($data,'没有数据',204);
        }else{
            return $this->create($data,'请求成功',200);
        }
    }

    //获取指定BB当天喂养且为有效的记录次数
    public function getNum(Request $request){

        $data = $request->param();
        $map = [];
        $map[] = [
            ['user_id','=',$data['user_id']],
            ['bb_id','=',$data['bb_id']]
        ];


        $data = Milk::where($map)->where('status',0)->whereDay('create_time')->count('bb_id');

        return $this->create($data,'请求成功',200);

    }

    //修改/调整喂养记录
    public function editBabyLog(Request $request,$id){

        $data = $request->param();//获取修改的数据

        $checkDb = Milk::where('id',$id)->find();

        if (empty($checkDb)){
            return $this->create($data,'没有数据',400);
        }else{

            $dbResult = Milk::update($data)->getData('id');

            return $this->create($dbResult,'请求成功',200);


        }

    }

    //获取一条数据/测试用
    public function readone($id){

        //验证输入的参数合法性，参数为整型
        if (!Validate::isInteger($id)){
            return $this->create([],'参数不合法',400);
        }

        //查找指定小孩ID的最近一条记录
        $data = Milk::where('id',$id)->field('content,realitycontent,status')->find();

        if (empty($data)){
            return $this->create($data,'没有数据',204);
        }else{
            return $this->create($data,'请求成功',200);
        }

    }


    //添加宝宝信息
    public function addBaby(Request $request){

        //获取表单数据
        $data = $request->param();

        $chkData = Baby::where('user_id',$data['user_id'])->find();

        if (empty($chkData)){
            //首次添加宝宝将其设置为默认，即ischoose=1
            $data['ischoose']=1;
        }

//        halt($data);

        //同一个用户下，宝宝不能同名，一个宝宝只能添加一次，当前用户下检查同名宝宝
        $chkData = Baby::where('user_id',$data['user_id'])
            ->where('babynike',$data['babynike'])
            ->find();


        if (!empty($chkData)){

            return $this->create([],'不能重复添加',400);

        }

        //写入数据并返回ID
        $id = Baby::create($data)->getData('id');

        if (empty($id)){
            return $this->create([],'写入失败',400);
        }else{
            return $this->create($id,'写入成功',200);
        }

    }


    //获取用户添加的宝宝信息
    public function getBaby(Request $request){
        $uid = $request->param('uid');

        $data = Baby::where('user_id',$uid)->field('id,babynike,ischoose')->select();

        if ($data->isEmpty()){
            return $this->create([],'没有数据',400);
        }else{
            return $this->create($data,'请求成功',200);
        }
    }


    //微信授权登录，绑定用户，获取用户信息并入库
    public function getuserinfo(Request $request){

        $data          = $request->param();
        $uid           = $data['uid'];
        $code          = $data['code'];
        $iv            = urldecode($data['iv']);//前端encodeURIComponent编码传过来再解码
        $encryptedData = $data['encryptedData'];

        //调用封装的小程序请求,获取openid和session_key
        $reSalt        = $this->getWx($code);
        $openid        = $reSalt['openid'];
        $session_key   = $reSalt['session_key'];

        //数据签名校验
        $signature     = $request->param('signature','','trim');
        $signature2    = sha1($data['rawData'].$session_key);
        if ($signature != $signature2) {
            return $this->create([$signature,$signature2],'数据签名校验失败',205);
        }

        // 通过session_key解密用户数据,并保存在数据库中
        $result = $this->decryUser($iv,$encryptedData,$session_key);
        $result = json_decode($result,true);

        //自定义规则生成第三方session,返回给前端存储在本地，用于每次请求服务器时的校验
//        $session3rd  = null;
//        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
//        $max = strlen($strPol)-1;
//        for($i=0;$i<16;$i++){
//            $session3rd .=$strPol[rand(0,$max)];
//        }

        $session3rd = md5($session_key.$openid);
        $reData['session3rd'] = $session3rd;


        //通过openid检查该用户是否有注册过，没有则执行更新/绑定操作
        //TODO 通过本地账户查询是否有绑定过openid，待优化 2022-04-07
        //如果换了个手机，uid肯定会变，那么再次发起绑定则会出现问题
        //所以还需要查询openid是否已经存在，存在则改变本地uid，且更新session
        $chkUser = Members::where('openid',$openid)->field('id,openid')->find();

        if (empty($chkUser)){
            //openid记录为空，说明没有绑定记录

            $findUid = Members::where('id',$uid)->find();
            if (empty($findUid)){
                return $this->create(null,'参数错误',204);
            }else{
                //绑定
                $updateUser = Members::update([
                    'id'        =>$uid,
                    'sessionkey'=>$session_key,
                    'nickName'  =>$result['nickName'],
                    'openid'    =>$openid,
                    'gender'    =>$result['gender'],
                    'avatarurl' =>$result['avatarUrl'],
                    'session3rd'=>$session3rd
                ]);
            }

        }else{
            //绑定过的
            if($chkUser['id']==$uid){
                //判断当前uid是否跟绑定了openid的uid一致
                $updateUser = Members::update([
                    'sessionkey'=>$session_key,
                    'session3rd'=>$session3rd],['id'=>$uid]);
            }else{
                //连同正确的Uid和session3rd给前端；等同于换了手机的场景
                $reData['uid'] = $chkUser['id'];
            }
        }

        //把解密过的用户基本信息直接传到前端
        $reData['nickName'] = $result['nickName'];
        $reData['avatarUrl'] = $result['avatarUrl'];

        //返回登录状态
        return $this->create($reData,'绑定成功',200);

    }


    //微信 解密用户信息
    private function decryUser($iv,$encData,$sessionKey){

        //无需额外引入 "@WXBizDataCrypt.php"，自动加载;

        $APPID = "wx860f12977678e529";

        $pc = new \WXBizDataCrypt($APPID, $sessionKey);//无需引入，直接实例化
        $errCode = $pc->decryptData($encData, $iv, $data );

        if ($errCode != 0) {

            return $errCode;
        }

        return $data;


    }

    // 微信获取openid/sessionKey
    private function getWx($code)
    {

        $APPID = "wx860f12977678e529";
        $SECRET = "XXXXXXXXXXXXXXXX";
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$APPID}&secret={$SECRET}&js_code={$code}&grant_type=authorization_code";

        $curl = curl_init(); // 启动一个CURL会话

        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_HEADER, 0);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象

        //检查请求状态
        if($tmpInfo===false){
            $msg    = curl_error($tmpInfo);
            return $msg;
        }

        //关闭URL请求
        curl_close($curl);

        $result = json_decode($tmpInfo, true);

        return $result;
    }

}